var express = require('express');
var router = express.Router();
var db=require("mongoose");
var mes=require("../mondels/mond.js");
var mess=db.model('mes');
var users=db.model("users");

/* GET home page. */
router.get('/', function(req, res, next) {
    mess.find( function (err, docs) {
        if(err)
        {
            console.log('用户名或密码');
            return res.redirect('/hello');
        }
        else {
            if (docs == "") {
                console.log('用户名或密码不正确');
                return res.redirect('/hello');
            }
            else{
                res.render('index', {title: 'Express', docs: docs});
            }
        }
    });
});
router.use("/bar",function(req,res){
    var b="12345";
    res.redirect("ajaxS/users/12345");
});
router.post("/",function(req,res){
    var username=req.body['username'],
        userpassword=req.body['userpassword'];
    users.findOne({name:username,password:userpassword},function(err,docs){
        if(err)
        {
            console.log(err);
        }
        console.log(docs);
        if(docs==null)
        {
            console.log('用户名或密码不正确');
            res.locals.error='用户名或密码有误';
            res.render('index', {title: 'Express', docs: docs});
        }
        else
        {
            console.log("success");
            return res.render("hello",{ me: '大家好',se:"呃呃呃"})
        }
    });
    console.log(username+"---------"+userpassword);
});
function findemail(userid)
{
    users.find({name:userid},function(err,docs){
        if(err){
            return false;
        }else
        {
            if(docs==null)
            {
                return false;
            }
            else{
                return true;
            }
        }
    });
}
router.use("/upt",function(req,res){
    if( findemail("123")) {
        var leth = Math.random() * 10 + 4;
        var newpass = 'a';
        for (var i = 0; i < leth; i++) {
            newpass = newpass + (Math.random() * 10).toFixed(0);
        }
        console.log(newpass);
        users.update({name: "123"}, {password: newpass}, {multi: true}, function (err, numberAffected, raw) {
            if (err) {
                console.log(err);
                res.write('{"status":"405","message":"用户名不存在，请确认你的用户名正确"}');
                res.end();
            }
            else {

                res.write('{"status":"200","message":"成了"}');
                res.end();
            }
        });
    }else{
        res.write('{"status":"407","message":"用户名不存在，请确认你的用户名正确"}');
        res.end();
    }
});
module.exports = router;
